<template>
    <div class="ding">
        <van-nav-bar title="确认订单" left-text="返回" left-arrow @click-left="onClickLeft" />
        <div class="ti">
            <div v-for="item in login" :key="item._id">
                提货人
                {{ item.loginname }}
                {{ item.loginpass }}
                <van-button type="primary" text="编辑" @click="edit(item)"
                    style="background: white;border:none;color:red;margin-left: 80px;" />
            </div>
            <van-dialog v-model:show="show" title="编辑提货人" show-cancel-button>
                <van-form>
                    <van-cell-group inset>
                        <van-field v-model="loginname" name="提货人" label="提货人" />
                        <van-field v-model="loginpass" name="手机号" label="手机号" />
                    </van-cell-group>
                </van-form>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit" @click="updLogin">
                        提交
                    </van-button>
                </div>
            </van-dialog>
        </div>
        <div class="zi">
            自提点：<button @click="ditu"
                style="border:0;height: 30px;background: none;color: red;float: right;padding-right: 13px;">切换</button><br />
            {{ address }}
        </div>
        <div class="box">
            <span style="color:darkgray">明日16:00可提货</span>
            <span style="float: right;color:darkgray">共{{ totalSelectedCount }}件</span>
            <div v-for="item in shop" :key="item._id" id="list_item" style="margin-top: 10px;">
                <div id="item_img">
                    <img :src="item.img" alt="" style="width:100%;height:100%"
                        @click="router.push(`/xiangs?_id=${item._id}`)">
                </div>
                <div id="item_con">
                    <div class="ctitle">
                        {{ item.name }}&nbsp;&nbsp;&nbsp;&nbsp;
                        100g/包&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <span style="float: right;">共{{ item.num }}件</span>
                    </div>
                    <div class="cfot">
                        <div class="cfot_left">
                            <span style="color:red;">￥{{ item.price }}</span>
                            <span class="del">{{ item.original }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer" style="margin-top: 10px;">
            <!-- 优惠券单元格 -->
            <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
            <!-- 优惠券列表 -->
            <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
                <van-coupon-list :coupons="coupons" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons"
                    @change="onChange" @exchange="onExchange" />
            </van-popup>
        </div>
        <div class="footer" style="font-size:13px;padding-left: 15px;width: 86%;">
            商品优惠
            <span style="color:red;float: right;">
                ￥{{ chosenCoupon >= 0 && coupons[chosenCoupon] && coupons[chosenCoupon].value ?
                    (coupons[chosenCoupon].value / 100).toFixed(2) : '0.00' }}
            </span>
        </div>
        <div class="footer" style="font-size:13px;padding-left: 15px;width: 86%;">
            商品总额
            <span style="float:right">{{ totalPrice }}</span>
        </div>
        <div class="footer" style="margin-top: 10px;font-size:13px;padding-left: 15px;width: 86%;">备注:
            <input type="text" style="border: none;height: 15px;" placeholder="请输入" />
        </div>
        <div class="zhi">
                <div class="zhi1">
                    <span>待支付</span>
                    <span style="color:red;">￥{{ shengPrice }}</span>
                    <van-button type="danger" @click="getZhi" round style="margin-top:30px">立即支付</van-button>
                </div>
        <TabsView/>

        </div>
    </div>
</template>

<script setup lang="ts">
const onClickLeft = () => history.back();
import { onMounted, ref, computed, reactive } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
const router = useRouter()
import TabsView from '../TabsView.vue';
import { useStore } from '@/store/pinia'
const store = useStore()
// 提货人
const login = ref([])
const show = ref(false);
const loginname = ref('')
const loginpass = ref('')
const loginId = ref('')
const address = ref('')
const getLogin = async () => {
    const { data } = await axios.get('http://localhost:3000/login')
    login.value = data.login
}
const edit = (item) => {
    show.value = true
    loginname.value = item.loginname
    loginpass.value = item.loginpass
    loginId.value = item._id
}
const updLogin = async () => {
    const { data } = await axios.put('http://localhost:3000/updlogin', {
        _id: loginId.value,
        loginname: loginname.value,
        loginpass: loginpass.value
    })
    if (data.code === 200) {
        console.log('修改成功')
        show.value = false; // 关闭对话框
        await getLogin(); // 刷新数据
    }
}
// 商品信息
const shop = ref([])
const getShop = async () => {
    const { data } = await axios.get('http://localhost:3000/shop')
    shop.value = data.shop
    ids.value = shop.value.map(item => item._id)
    localStorage.setItem('shop', JSON.stringify(shop.value));
}
onMounted(() => {
    getLogin()
    getShop()
    address.value = localStorage.getItem('address')
    console.log(address.value)
    console.log(store);
})
// 自提点
const ditu = () => {
    router.push('/ti');
}
// 优惠券
const coupon = {
    available: 1,
    condition: '无门槛\n最多优惠12元',
    reason: '',
    value: 150,
    name: '优惠券名称',
    startAt: 1489104000,
    endAt: 1514592000,
    valueDesc: '1.5',
    unitDesc: '元',
};
const newCoupon = {
    available: 1,
    condition: '无门槛\n最多优惠12元',
    reason: '',
    value: 300,              // 优惠券的实际优惠金额（单位：分）
    name: '新优惠券名称',
    startAt: 1689104000,      // 开始时间（时间戳）
    endAt: 1694592000,        // 结束时间（时间戳）
    valueDesc: '3',           // 优惠金额的描述（单位：元）
    unitDesc: '元',            // 优惠单位
};
const coupons = ref([coupon, newCoupon]);
const showList = ref(false);
const chosenCoupon = ref(-1);
const onChange = (index) => {
    showList.value = false;
    chosenCoupon.value = index;
};
const onExchange = (code) => {
    coupons.value.push(coupon);
};
// 计算总价
const isCheckAll = ref(false);
const isIndeterminate = ref(false);
const totalPrice = computed(() => {
    let total = 0;
    shop.value.forEach(item => {
        total += item.price * item.num;

    });
    return total.toFixed(2);
});
// 计算节省了多少钱
const shengPrice = computed(() => {
    let total = 0;
    if (chosenCoupon.value >= 0) {
        console.log(chosenCoupon.value)
        total = coupons.value[chosenCoupon.value].value;
        console.log(total)
    }
    return (totalPrice.value - total / 100).toFixed(2)
});
// 对去下单总数进行计算
const totalSelectedCount = computed(() => {
    return shop.value.reduce((total, item) => total + item.num, 0);
});

// 支付
let list = ref({
    price: shengPrice,
})
const ids = ref([]);
const getZhi = async () => {
    try {
         await axios.post('http://localhost:3000/delAllshop', { ids: ids.value });
        const data = {
            orderId: Date.now(),
            price: list.value.price,
            name: '支付'
        };
        const res = await axios({
            url: 'http://localhost:3000/api/payment',
            method: 'post',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            data: data,
        });
        console.log(res);
        window.open(res.data.data.result, '_self');
    } catch (error) {
        console.error(error);
    }
}

</script>

<style scoped lang="scss">
.ding {
    width: 100%;
    height: 100%;
    background: rgb(247, 247, 247);
}
.sticky-bottom {
  position: sticky;
  bottom: 0;
  z-index: 1000; /* 设置较高的 z-index 确保在全局底部粘性布局之上 */
}
.ti {
    width: 90%;
    height: 70px;
    display: flex;
    justify-content: space-between;
    font-weight: 700;
    line-height: 70px;
    margin: 0 auto;
    border-bottom: 1px solid #ccc;
    background: white;
}

.zi {
    width: 90%;
    height: 70px;
    margin: 0 auto;
    font-weight: 700;
    border-bottom: 1px solid #ccc;
    background: white;
}

.box {
    width: 90%;
    min-height: 100px;
    margin: 0 auto;
    background: white;
    margin-top: 10px;
}

#list_item {
    width: 90%;
    height: 145px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    border-bottom: 1px solid rgb(214, 214, 214);

    #item_img {
        width: 110px;
        height: 110px;
    }

    #item_con {
        width: 60%;
        height: 100%;
        color: rgb(117, 117, 117);
        margin-left: 10px;

        .ctitle {
            width: 100%;
            height: 30px;
        }

        .cfot {
            width: 100%;
            height: 65px;
            margin-top: 5px;
            display: flex;
            justify-content: space-between;
            margin-top: 60px;

            .cfot_left {
                width: 100%;
                height: 100%;

                .del {
                    padding-left: 30px;
                    height: 10px;
                    line-height: 10px;
                    text-decoration: line-through;
                }
            }
        }
    }
}

.footer {
    width: 90%;
    height: 70px;
    margin: 0 auto;
    border-bottom: 1px solid rgb(214, 214, 214);
    line-height: 70px;
    background: white;
}

.zhi {
    width: 100%;
    height: 50px;
    line-height: 100px;
    background: white;
    margin-top: 40px;
    font-weight: 300;
    font-size: 20px;
    margin-bottom: 100px;
}

.zhi1 {
    width: 100%;
    height: 150px;
    display: flex;
    justify-content: space-between;
    background: white;
}
</style>